﻿using bwtSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Collections.Concurrent;
using Timer = System.Timers.Timer;
using static AutoTestCommunication_Service.Public;
using NPOI.SS.Formula.Functions;
using System.ComponentModel;
using NPOI.OpenXmlFormats.Dml;

namespace AutoTestCommunication_Service.Class
{
    public class BWTTcpClientClass
    {
        public BWTTcpClient BWTTcpClient { get; set; }
        public string ip { get; set; }
        public string port { get; set; }


        public int SRIndex { get; set; }
        public int DataReadIndex { get; set; }

        public ConcurrentDictionary<int, string> sendCD { get; set; }
        public ConcurrentDictionary<int, string> revCD { get; set; }
        public ConcurrentDictionary<int, string> DataReadCMD { get; set; }

        public Ping Ping { get; set; }
        public double 第一峰值 { get; set; }
        public double 第二峰值 { get; set; }
        public double 第三峰值 { get; set; }

        public double 拉曼差值 { get; set; }

        public double 差值 { get; set; }

        public double A1 { get; set; }
        public double A2 { get; set; }
        public double B1 { get; set; }
        public double B2 { get; set; }
        public double C1 { get; set; }
        public double C2 { get; set; }
        public double 初始值 { get; set; }

        public bool 已在线 { get; set; }
        public bool 已连接 { get; set; }

        public int RAMANS { get; set; }
    }

    internal class Raman
    {
        public static ConcurrentDictionary<string, Public.EquipmentParameters> EP = new ConcurrentDictionary<string, Public.EquipmentParameters>();
     
        private bwtSocket.BWTTcpServer tcpServer;

        public Timer mysqlbengyuanTimer = new Timer();
        public static Timer TestConnectionTimer = new Timer();
        public bool ServerOnline = true;
        public static bool IsTcpConnectTesting = false;
        public double PixelCoefficient;
        TreeViewItem TVSelectedNode;
        public static BindingLB BDHostHoststate = new BindingLB();
        public static BindingLB BDopticalfiberstate = new BindingLB();
        public static BindingLB BDPumpsourcestate = new BindingLB();
        public static BindingLB BDjiandaoyunstate = new BindingLB();
        public static BindingLB BDmessage = new BindingLB();

        public static BindingLB BDstarttime = new BindingLB();
        public static BindingLB BDendtime = new BindingLB();
        public static BindingLB BDcosttime = new BindingLB();
        public string CurrentIP = "";

        public static ConcurrentDictionary<int, string> sendCD = new ConcurrentDictionary<int, string>();
        public static int SRIndex = 0, DataReadIndex = 0;
        public static ConcurrentDictionary<int, string> revCD = new ConcurrentDictionary<int, string>();
        public static ConcurrentDictionary<int, string> DataReadCMD = new ConcurrentDictionary<int, string>();
        public static ConcurrentDictionary<int, BWTTcpClientClass> BWTTcpClientClassCD = new ConcurrentDictionary<int, BWTTcpClientClass>();
        public string sendx1str, sendx2str;
        public string sendy1str, sendy2str;
        public static Timer LoginTimer = new Timer();
        public static Timer DataReaderTimer = new Timer();
        public static double 第一峰值, 第二峰值, 差值;
        public static double A1, A2, B1, B2, C1, C2, 初始值 = 900;
        BWTTcpClient tcpClient;
        public static ConcurrentDictionary<int, string> IPCD = new ConcurrentDictionary<int, string>();    
        public static ConcurrentDictionary<string, int> IPIndexCD = new ConcurrentDictionary<string, int>();
        string ip = string.Empty;
        string port = string.Empty;
        public static bool ramancomplete=false;
        public static bool IsTesting =false;

        public static void DataPreparation()
        {

            IPCD.TryAdd(0, "192.168.29.91");
            IPCD.TryAdd(1, "192.168.29.92");
            IPCD.TryAdd(2, "192.168.29.93");
            IPIndexCD.TryAdd("192.168.29.91", 0);
            IPIndexCD.TryAdd("192.168.29.92", 1);
            IPIndexCD.TryAdd("192.168.29.93", 2);

            string strmsg;

            strmsg = "open" + " ";
            strmsg = strmsg + @"""anonymous""";
            sendCD.TryAdd(0, strmsg);
            strmsg = " ";
            sendCD.TryAdd(1, strmsg);
            strmsg = "*idn?";
            sendCD.TryAdd(2, strmsg);

            strmsg = "*RST";
            sendCD.TryAdd(3, strmsg);
            strmsg = "CFORM1";
            sendCD.TryAdd(4, strmsg);
            strmsg = ":sens:wav:cent 1050nm";
            sendCD.TryAdd(5, strmsg);
            strmsg = ":sens:wav:span 300nm";
            sendCD.TryAdd(6, strmsg);
            strmsg = ":sens:sens mid";
            sendCD.TryAdd(7, strmsg);

            strmsg = ":init:smode 1";
            sendCD.TryAdd(8, strmsg);
            strmsg = "*CLS";
            sendCD.TryAdd(9, strmsg);
            //========================================================================
            strmsg = ":init";//扫描
            DataReadCMD.TryAdd(0, strmsg);

            strmsg = ":stat:oper:even?";//获取状态
            DataReadCMD.TryAdd(1, strmsg);

            strmsg = "trace:x? tra,1,1";//起始值900
            DataReadCMD.TryAdd(2, strmsg);

            初始值 = 900;
            //1078-1082//1130-1140//间隔2
            A1 = (1078 - 初始值) * 5 + 1;
            A2 = (1082 - 初始值) * 5 + 1;
            strmsg = "trace:y? tra," + A1 + "," + A2;//第一点
                                                     //strmsg = "trace:y? tra,891,911";//第一点
            DataReadCMD.TryAdd(3, strmsg);

            B1 = (1130 - 初始值) * 5 + 1;
            B2 = (1140 - 初始值) * 5 + 1;
            strmsg = "trace:y? tra," + B1 + "," + B2;//第一点
                                                     //strmsg = "trace:y? tra,1151,1201";//第二点
            DataReadCMD.TryAdd(4, strmsg);

            C1 = (998 - 初始值) * 5 + 1;
            C2 = (1002 - 初始值) * 5 + 1;
            strmsg = "trace:y? tra," + B1 + "," + B2;//第一点
                                                     //strmsg = "trace:y? tra,1151,1201";//第二点
            DataReadCMD.TryAdd(4, strmsg);
            //========================================================================
            strmsg = "AUTHENTICATE CRAM-MD5.";
            revCD.TryAdd(0, strmsg);
            strmsg = "ready";
            revCD.TryAdd(1, strmsg);
            strmsg = "YOKOGAWA,AQ6370,91G309852,02.11";
            revCD.TryAdd(2, strmsg);

            BWTTcpClient.pushSockets = new PushSockets(Rec);
            建立结构初始化();
        
            Task.Run(() => { RunWorker(); });
            //Task.Run(() => { TestConnection(); });
        }
        public static void TimerSetting()
        {
            LoginTimer.AutoReset = false;
            LoginTimer.Interval = 10;
            LoginTimer.Enabled = false;
            LoginTimer.Elapsed += LoginTimerEvent;

        }
        private static void LoginTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                LoginTimer.Enabled = false;
                bool TIMEREnabled = false;
                for (int i = 0; i < BWTTcpClientClassCD.Count; i++)
                {
                    if (BWTTcpClientClassCD[i].已连接)
                    {
                        BWTTcpClientClassCD[i].BWTTcpClient.SendData(BWTTcpClientClassCD[i].sendCD[BWTTcpClientClassCD[i].SRIndex]);
                        BWTTcpClientClassCD[i].SRIndex++;
                        if (BWTTcpClientClassCD[i].SRIndex < BWTTcpClientClassCD[i].sendCD.Count)
                        {
                            TIMEREnabled = true;
                        }
                        else
                        {
                            BWTTcpClientClassCD[i].BWTTcpClient.SendData(BWTTcpClientClassCD[i].DataReadCMD[BWTTcpClientClassCD[i].DataReadIndex]);
                            DigitalService.CreatLog(BWTTcpClientClassCD[i].ip, "LoginTimerEvent");
                            DataReader();
                        }
                    }
                }
                LoginTimer.Enabled = TIMEREnabled;
            }
            catch (Exception ex)
            {
                TraceMethodInfo(ex.Message + ex.StackTrace);
            }
        }
        public static void DataReader()
        {
            try
            {
                for (int i = 0; i < BWTTcpClientClassCD.Count; i++)
                {
                    if (BWTTcpClientClassCD[i].已连接 & BWTTcpClientClassCD[i].SRIndex == BWTTcpClientClassCD[i].sendCD.Count)
                    {

                        if (BWTTcpClientClassCD[i].DataReadIndex == 0)
                        {
                            BWTTcpClientClassCD[i].DataReadIndex++;
                            DigitalService.CreatLog(BWTTcpClientClassCD[i].ip, "DataReader");
                            BWTTcpClientClassCD[i].BWTTcpClient.SendData(BWTTcpClientClassCD[i].DataReadCMD[BWTTcpClientClassCD[i].DataReadIndex]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TraceMethodInfo(ex.Message + ex.StackTrace);
            }  //DataReaderTimer.Enabled = true;
         }

        static BackgroundWorker _Worker = new BackgroundWorker();

        private static void RunWorker()
        {
            _Worker.DoWork += new DoWorkEventHandler(_Worker_DoWork);
            //无限循环
            while (true)
            {
                if (!_Worker.IsBusy)
                {
                    _Worker.RunWorkerAsync();
                }
                else
                {
                    //休眠一段时间,不用那么频繁的操作
                    Thread.Sleep(2000);
                }
            }
        }
        static void _Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (!IsTesting)
                {
                    for (int i = 0; i < BWTTcpClientClassCD.Count; i++)
                    {
                        if (TestConnection(BWTTcpClientClassCD[i]))
                        {
                            BWTTcpClientClassCD[i].已在线 = true;
                            if (BWTTcpClientClassCD[i].已在线 == true & BWTTcpClientClassCD[i].已连接 == false)
                            {
                                BWTTcpClientClassCD[i].BWTTcpClient.InitSocket(BWTTcpClientClassCD[i].ip, int.Parse(BWTTcpClientClassCD[i].port));
                                BWTTcpClientClassCD[i].BWTTcpClient.Start();
                                DigitalService.CreatLog(BWTTcpClientClassCD[i].ip, BWTTcpClientClassCD[i].ip + "已连接");
                                BWTTcpClientClassCD[i].已连接 = true;
                            }
                        }
                        else
                        {
                            BWTTcpClientClassCD[i].已在线 = false;
                            BWTTcpClientClassCD[i].已连接 = false;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                TraceMethodInfo(ex.Message + ex.StackTrace);
                return;
            }

        }
        public static void TestConnection()
        {
            try
            {
                while (true)
                {
                    if (!IsTesting)
                    {
                        //for (int i = 0; i < IPCD.Count; i++)
                        //{
                        //    if (TestConnection(IPCD[i]))
                        //    {
                        //        BWTTcpClientClassCD[i].已在线 = true;
                        //        if (BWTTcpClientClassCD[i].已在线 == true & BWTTcpClientClassCD[i].已连接 == false)
                        //        {
                        //            BWTTcpClientClassCD[i].BWTTcpClient.InitSocket(BWTTcpClientClassCD[i].ip, int.Parse(BWTTcpClientClassCD[i].port));
                        //            BWTTcpClientClassCD[i].BWTTcpClient.Start();
                        //            DigitalService.CreatLog(BWTTcpClientClassCD[i].ip, BWTTcpClientClassCD[i].ip+ "已连接");
                        //            BWTTcpClientClassCD[i].已连接 = true;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        BWTTcpClientClassCD[i].已在线 = false;
                        //        BWTTcpClientClassCD[i].已连接 = false;
                        //    }
                        //}
                    }
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Task.Run(() => { TestConnection(); });
                TraceMethodInfo(ex.Message + ex.StackTrace);
            }
        }
        public static void Rec(Sockets sks)
        {
            try
            {
                if (sks.ex != null)
                {
                    if (sks.ClientDispose == true)
                    {
                        //MessageBox.Show("1");
                        //由于未知原因引发异常.导致客户端下线.   比如网络故障.或服务器断开连接.
                        DigitalService.CreatLog(sks.Ip.Address.ToString(), "Raman客户端下线1");
                    }
                }
                else if (sks.Offset == 0)
                {
                    for (int i = 0; i < IPCD.Count; i++)
                    {
                        if(sks.Ip != null)
                        {
                            if (sks.Ip.Address.ToString() == BWTTcpClientClassCD[i].ip & BWTTcpClientClassCD[i].已连接 == true)
                            {
                                DigitalService.CreatLog(sks.Ip.Address.ToString(), "Raman客户端下线2");
                                BWTTcpClientClassCD[i].已连接 = false;
                                BWTTcpClientClassCD[i].BWTTcpClient.Stop();
                            }
                        }
                    }
                    //MessageBox.Show("2");
                    //客户端主动下线
                    //DigitalService.CreatLog(sks.Ip.Address.ToString(),"Raman客户端下线2") ;
                }
                else
                {

                    byte[] buffer = new byte[sks.Offset];
                    Array.Copy(sks.RecBuffer, buffer, sks.Offset);
                    string str = Encoding.UTF8.GetString(buffer).TrimEnd('\r', '\n');
                    string[] yunArray = str.Split(new string[] { ",", ":" }, StringSplitOptions.RemoveEmptyEntries);
                    int INDEX = IPIndexCD[sks.Ip.Address.ToString()];

                    if (BWTTcpClientClassCD[INDEX].SRIndex < BWTTcpClientClassCD[INDEX].sendCD.Count)
                    {

                    }
                    else//获取数据
                    {
                        if (yunArray.Count() == 4) return;
                        double[] DBvalue = new double[yunArray.Count()];
                        for (int i = 0; i < yunArray.Count(); i++)
                        {
                            DBvalue[i] = Convert.ToDouble(yunArray[i]);
                        }

                        if (BWTTcpClientClassCD[INDEX].DataReadIndex == 1)
                        {
                            if (DBvalue[0] == 0)
                            {
                                IsTesting = true;
                                BWTTcpClientClassCD[INDEX].DataReadIndex++;
                            }

                        }
                        else if (BWTTcpClientClassCD[INDEX].DataReadIndex == 2)
                        {
                            string strmsg;
                            BWTTcpClientClassCD[INDEX].初始值 = DBvalue[0] * 1.0E+9;
                            //1078-1082//1130-1140//间隔2
                            BWTTcpClientClassCD[INDEX].A1 = (1078 - 初始值) * 5 + 1;
                            BWTTcpClientClassCD[INDEX].A2 = (1082 - 初始值) * 5 + 1;
                            strmsg = "trace:y? tra," + BWTTcpClientClassCD[INDEX].A1 + "," + BWTTcpClientClassCD[INDEX].A2;//第一点
                            BWTTcpClientClassCD[INDEX].DataReadCMD[3] = strmsg;                            //strmsg = "trace:y? tra,891,911";//第一点
                                                                                                           //DataReadCMD.TryAdd(3, strmsg);
                            BWTTcpClientClassCD[INDEX].B1 = (1130 - 初始值) * 5 + 1;
                            BWTTcpClientClassCD[INDEX].B2 = (1140 - 初始值) * 5 + 1;
                            strmsg = "trace:y? tra," + BWTTcpClientClassCD[INDEX].B1 + "," + BWTTcpClientClassCD[INDEX].B2;//第一点
                            BWTTcpClientClassCD[INDEX].DataReadCMD[4] = strmsg;                       //strmsg = "trace:y? tra,1151,1201";//第二点
                                                                                                      //DataReadCMD.TryAdd(4, strmsg);
                            BWTTcpClientClassCD[INDEX].C1 = (998 - 初始值) * 5 + 1;
                            BWTTcpClientClassCD[INDEX].C2 = (1002 - 初始值) * 5 + 1;
                            strmsg = "trace:y? tra," + BWTTcpClientClassCD[INDEX].C1 + "," + BWTTcpClientClassCD[INDEX].C2;//第一点
                            BWTTcpClientClassCD[INDEX].DataReadCMD[5] = strmsg;                       //strmsg = "trace:y? tra,1151,1201";//第二点
                                                                                                      //DataReadCMD.TryAdd(4, strmsg);
                            BWTTcpClientClassCD[INDEX].DataReadIndex++;
                            DigitalService.CreatLog(sks.Ip.Address.ToString(), "Raman步骤2");
                        }
                        else if (BWTTcpClientClassCD[INDEX].DataReadIndex == 3)
                        {
                            BWTTcpClientClassCD[INDEX].第一峰值 = DBvalue.Max();
                            BWTTcpClientClassCD[INDEX].DataReadIndex++;
                            DigitalService.CreatLog(sks.Ip.Address.ToString(), "Raman步骤3");
                        }
                        else if (BWTTcpClientClassCD[INDEX].DataReadIndex == 4)
                        {
                            BWTTcpClientClassCD[INDEX].第二峰值 = DBvalue.Max();
                            BWTTcpClientClassCD[INDEX].拉曼差值 = BWTTcpClientClassCD[INDEX].第一峰值 - BWTTcpClientClassCD[INDEX].第二峰值;
                            BWTTcpClientClassCD[INDEX].DataReadIndex++;
                            DigitalService.CreatLog(sks.Ip.Address.ToString(), "Raman步骤4");
                        }
                        else if (BWTTcpClientClassCD[INDEX].DataReadIndex == 5)
                        {
                            BWTTcpClientClassCD[INDEX].第三峰值 = DBvalue.Max();
                            BWTTcpClientClassCD[INDEX].差值 = BWTTcpClientClassCD[INDEX].第一峰值 - BWTTcpClientClassCD[INDEX].第三峰值;
                            DigitalService.CreatLog(sks.Ip.Address.ToString(), "Raman步骤5");
                            //sendCommand();
                            IsTesting = false;
                            ramancomplete = true;
                            return;
                        }
                        BWTTcpClientClassCD[INDEX].BWTTcpClient.SendData(BWTTcpClientClassCD[INDEX].DataReadCMD[BWTTcpClientClassCD[INDEX].DataReadIndex]);
                        return;
                    }

                }

            }
            catch (Exception ex)
            {
                TraceMethodInfo(ex.Message + ex.StackTrace);
            }

        }
        public static void 建立结构初始化()
        {
            for (int i = 0; i < IPCD.Count; i++)
            {
                BWTTcpClientClass P = new BWTTcpClientClass()
                {
                    BWTTcpClient = new BWTTcpClient(),
                    Ping=new Ping(),
                    ip = IPCD[i],
                    port = "10001",
                    SRIndex = 0,
                    DataReadIndex = 0,
                    sendCD = sendCD,
                    revCD = revCD,
                    DataReadCMD = DataReadCMD,
                    第一峰值 = 0,
                    第二峰值 = 0,
                    差值 = 0,
                    拉曼差值 = 0,
                    A1 = 0,
                    A2 = 0,
                    B1 = 0,
                    B2 = 0,
                    初始值 = 0,
                    已连接 = false,
                    已在线 = false,
                };
                BWTTcpClientClassCD.TryAdd(i, P);
            }
        }
        public static void 数据初始化()
        {
            for (int i = 0; i < BWTTcpClientClassCD.Count; i++)
            {
                BWTTcpClientClassCD[i].SRIndex = 0;
                BWTTcpClientClassCD[i].DataReadIndex = 0;

                BWTTcpClientClassCD[i].第一峰值 = 0;
                BWTTcpClientClassCD[i].第二峰值 = 0;
                BWTTcpClientClassCD[i].差值 = 0;
                BWTTcpClientClassCD[i].拉曼差值 = 0;
                BWTTcpClientClassCD[i].A1 = 0;
                BWTTcpClientClassCD[i].A2 = 0;
                BWTTcpClientClassCD[i].B1 = 0;
                BWTTcpClientClassCD[i].B2 = 0;
                BWTTcpClientClassCD[i].初始值 = 0;
            }
        }

        #region 采用Socket方式，测试服务器连接
        /// <summary>
        /// 采用Socket方式，测试服务器连接
        /// </summary>
        /// <param name="host">服务器主机名或IP</param>
        /// <param name="port">端口号</param>
        /// <param name="millisecondsTimeout">等待时间：毫秒</param>
        /// <returns></returns>
        public static bool TestConnection(BWTTcpClientClass BWTTcpClient)
        {
            try
            {
                bool TestResult = false;
                IsTcpConnectTesting = true;
                int timeout = 2000;
                PingReply pingReply = BWTTcpClient.Ping.Send(BWTTcpClient.ip, timeout);

                if (pingReply.Status == IPStatus.Success)
                {
                    TestResult = true;
                }
                else
                {
                    TestResult = false;
                }
                IsTcpConnectTesting = false;
                return TestResult;
            }
            catch(Exception ex) 
            {
                TraceMethodInfo(ex.Message + ex.StackTrace);
                return false;
            }
        }
        #endregion        
    }
}
